/**
 * 试剂瓶页面
 */

import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import {
  Row,
  Col,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Space,
  message,
  Table,
  Popconfirm,
  Typography,
  Select,
  Tooltip,
} from "antd";

import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { ITStore } from "../../store";
import { ITBottle, ITDictValue, ITColumns } from "../../store/interfaces";

const { Text } = Typography;

const { Option } = Select;

type TProp = {
  store: ITStore;
};

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const inputwide = {
  width: "100%",
};

// 搜索和新增按钮组件
const SearchAddComp: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang },
      bottleStore: { changeShowAddEditBottleModal },
    } = store;

    const handleClickAdd = () => {
      changeShowAddEditBottleModal(true);
    };

    return (
      <Row style={{ marginBottom: 20 }}>
        <Col span={12}></Col>
        <Col span={12}>
          <Space wrap style={{ float: "right" }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleClickAdd}
            >
              {lang["langbuttonadd"]}
            </Button>
          </Space>
        </Col>
      </Row>
    );
  })
);

// 新增 编辑试剂瓶弹窗
const AddEditBottleModal: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang, langCur },
      bottleStore: {
        showAddEditBottleModal,
        addEditBottleLoading,
        changeShowAddEditBottleModal,
        editBottleData,
        addBottle,
        updateBottle,
        changeEditBottleData,
        getAllBottle,
      },
      dictionaryStore: { getDictValuesByKey },
    } = store;

    const [form] = Form.useForm();

    const [shapeOption, setShapeOption] = useState<ITDictValue[]>([]);

    useEffect(() => {
      setShapeOption(getDictValuesByKey("bottleshape"));
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
      if (editBottleData) {
        form.setFieldsValue(editBottleData);
      }
    }, [editBottleData, form]);

    const close = () => {
      form.resetFields();
      changeEditBottleData(null);
      changeShowAddEditBottleModal(false);
    };

    const formFinish = async (values: ITBottle) => {
      let result = null;
      let msg: string = "";
      if (editBottleData) {
        // 编辑
        result = await updateBottle(values);
        msg = lang["langmodifysuccess"];
      } else {
        // 新增
        const { id, ...addparam } = values;
        result = await addBottle(addparam);
        msg = lang["langaddsuccess"];
      }

      if (!result) {
        close();
        message.success(msg);
        getAllBottle();
      } else {
        const { msg } = result;
        message.error(msg);
      }
    };

    return (
      <Modal
        title={
          !!editBottleData ? lang["langeditbottle"] : lang["langaddbottle"]
        }
        open={showAddEditBottleModal}
        destroyOnClose={true}
        onOk={() => {
          form.submit();
        }}
        confirmLoading={addEditBottleLoading}
        onCancel={close}
      >
        <Form {...layout} form={form} name="bottleForm" onFinish={formFinish}>
          <Form.Item name="id" label="" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            name="name"
            label={lang["langname"]}
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="height"
            label={lang["langheight"]}
            rules={[{ required: true }]}
          >
            <InputNumber addonAfter={lang["langmmunit"]} style={inputwide} />
          </Form.Item>
          <Form.Item
            name="diameter"
            label={lang["langdiameter"]}
            rules={[{ required: true }]}
          >
            <InputNumber addonAfter={lang["langmmunit"]} style={inputwide} />
          </Form.Item>
          <Form.Item
            name="depth"
            label={lang["langdepth"]}
            rules={[{ required: true }]}
          >
            <InputNumber addonAfter={lang["langmmunit"]} style={inputwide} />
          </Form.Item>

          <Form.Item
            name="volume"
            label={lang["langvolume"]}
            rules={[{ required: true }]}
          >
            <InputNumber addonAfter={lang["langmlunit"]} style={inputwide} />
          </Form.Item>
          <Form.Item
            name="shape"
            label={lang["langshape"]}
            rules={[{ required: true }]}
          >
            <Select>
              {shapeOption.map(({ cnlabel, label, value, sort }) => (
                <Option key={sort} value={value}>
                  {langCur === "en" ? label : cnlabel}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    );
  })
);

// 试剂瓶列表
const BottleList: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang, langCur },
      bottleStore: {
        allLoading,
        getAllBottle,
        allBottle,
        delBottleLoading,
        changeEditBottleData,
        changeShowAddEditBottleModal,
        delteBottle,
      },
      dictionaryStore: { getDictValuesByKey },
    } = store;

    const [delData, setDelData] = useState<ITBottle | null>(null);

    const [renderData, setRenderData] = useState<ITBottle[]>([]);

    const [shapeOption, setShapeOption] = useState<ITDictValue[]>([]);

    useEffect(() => {
      setShapeOption(getDictValuesByKey("bottleshape"));
      getAllBottle();
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
      if (allBottle.length) {
        allBottle.forEach((item, index) => (item.key = index));
      }
      setRenderData(allBottle);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [allBottle]);

    const getShapeLabel = (value: string, _langCur: string) => {
      let label = "";
      shapeOption.some((item) => {
        if (item.value === value) {
          label = item.label;
          if (_langCur === "zhcn") {
            label = item.cnlabel;
          }
          return true;
        }
        return false;
      });
      return label;
    };

    const modifyItem = (data: ITBottle) => {
      changeEditBottleData(data);
      changeShowAddEditBottleModal(true);
    };

    const deleteItem = async (data: ITBottle) => {
      setDelData(data);
      const { id } = data;
      const res = await delteBottle({ id });
      if (!res) {
        getAllBottle();
        message.success(lang["langdeletesuccess"]);
        setDelData(null);
      }
    };

    const columns: ITColumns[] = [
      {
        title: lang["langname"],
        dataIndex: "name",
        key: "name",
      },
      {
        title: (
          <>
            <Text>{lang["langheight"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "height",
        key: "height",
      },
      {
        title: (
          <>
            <Text>{lang["langdiameter"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "diameter",
        key: "diameter",
      },
      {
        title: (
          <>
            <Text>{lang["langdepth"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "depth",
        key: "depth",
      },
      {
        title: (
          <>
            <Text>{lang["langvolume"]}</Text>
            <Text type="secondary"> ({lang["langmlunit"]})</Text>
          </>
        ),
        dataIndex: "volume",
        key: "volume",
      },
      {
        title: lang["langshape"],
        dataIndex: "shape",
        key: "shape",
        render: (txt: string) => {
          return getShapeLabel(txt, langCur);
        },
      },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        width: 110,
        align: "center",
        render: (_: string, record: ITBottle) => {
          return (
            <Space>
              <Tooltip title={lang["langedit"]}>
                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => {
                    modifyItem(record);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title={lang["langconfirmdel"]}
                onConfirm={() => {
                  deleteItem(record);
                }}
              >
                <Tooltip title={lang["langdelete"]}>
                  <Button
                    type="link"
                    danger
                    loading={delData?.id === record.id && delBottleLoading}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          );
        },
      },
    ];

    return (
      <Table
        bordered
        loading={allLoading}
        dataSource={renderData}
        columns={columns}
      />
    );
  })
);

const Bottle: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  return (
    <>
      {/* 搜索和新增按钮组件 */}
      <SearchAddComp />

      {/* 试剂瓶列表 */}
      <BottleList />

      {/* 新增 编辑试剂瓶弹窗 */}
      <AddEditBottleModal />
    </>
  );
};

export default inject("store")(observer(Bottle));
